<template>
  <el-table-column class-name="order-table-col">
    <template #default="scope">
      <ContentWrap
        :bodyStyle="{ padding: '10px', borderRadius: '0px' }"
        class="!border-rd-none !border-b-none mb-0! bg-[var(--el-table-header-bg-color)]!"
      >
        <el-row
          class="color-[#606266] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
        >
          <el-col :span="24">
            <div>
              <span>订单号码：{{ scope.row.no }}</span>
              <span class="ml-10px">销售时间：{{ formatDate(scope.row.tradeTime) }}</span>
              <span class="ml-10px">操作时间：{{ formatDate(scope.row.updateTime) }}</span>
              <span class="ml-10px">总欠款金额 ：</span>
              <span class="text-red">￥{{ floatToFixed2(scope.row.leavePrice) }}</span>
            </div>
          </el-col>
        </el-row>
      </ContentWrap>
      <el-table
        ref="activityOrderListRef"
        :border="true"
        :data="scope.row.items"
        :row-class-name="'table-col-row-class'"
        :span-method="spanMethod"
        style="width: 100%"
        @selection-change="
          (e) => {
            handleSelectionChange(e, scope.row)
          }
        "
      >
        <el-table-column type="selection" width="35" />

        <el-table-column min-width="260" align="center" prop="spuName" label="商品信息">
          <template #default="{ row }">
            <div class="flex">
              <div class="flex items-center">
                <div class="mr-[10px] flex items-center">
                  <el-image
                    :src="row.picUrl"
                    class="!h-[48px] !w-[48px] border-rd-4px"
                    @click="imagePreview(row.picUrl)"
                  >
                    <template #error>
                      <div class="image-slot">
                        <icon icon="ep:picture" />
                      </div>
                    </template>
                  </el-image>
                </div>

                <ElTooltip :content="row.spuName" placement="top">
                  <span class="overflow-ellipsis overflow-hidden">
                    {{ row.spuName }}
                    <el-tag v-for="property in row.properties" :key="property.propertyId">
                      {{ property.propertyName }}: {{ property.valueName }}
                    </el-tag>
                  </span>
                </ElTooltip>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" prop="price" min-width="85">
          <template #default="{ row }">
            {{ row.count }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="订单实售" prop="realPrice" min-width="85">
          <template #header>
            <div class="flex items-center justify-center">
              订单实售
              <el-popover
                :width="200"
                trigger="hover"
                placement="top"
                :content="NoteOnOrder.DINGDANSHISHOU"
              >
                <template #reference>
                  <Icon icon="ep:warning" class="m-l-2px" />
                </template>
              </el-popover>
            </div>
          </template>
          <template #default="{ row }"> {{ floatToFixed2(row.realPrice) }} 元 </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" min-width="85" prop="otherPrice">
          <template #header>
            <div class="flex items-center justify-center">
              实付金额
              <el-popover
                :width="200"
                trigger="hover"
                placement="top"
                :content="NoteOnOrder.SHIFUJINE"
              >
                <template #reference>
                  <Icon icon="ep:warning" class="m-l-2px" />
                </template>
              </el-popover>
            </div>
          </template>
          <template #default="{ row }">
            <span>{{ floatToFixed2(row.otherPrice) + '元' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="欠款金额" min-width="85" prop="arrearsPrice ">
          <template #header>
            <div class="flex items-center justify-center">
              欠款金额
              <el-popover
                :width="200"
                trigger="hover"
                placement="top"
                :content="NoteOnOrder.QIANKUANJINE"
              >
                <template #reference>
                  <Icon icon="ep:warning" class="m-l-2px" />
                </template>
              </el-popover>
            </div>
          </template>
          <template #default="{ row }">
            <span :class="{ 'text-red': row.arrearsPrice > 0 }">{{
              floatToFixed2(row.arrearsPrice) + '元'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="已还金额" min-width="85" prop="arrearsPrice ">
          <template #default="{ row }">
            <span :class="{ 'text-red': row.repayPrice > 0 }">{{
              floatToFixed2(row.repayPrice) + '元'
            }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="剩余欠款" min-width="85" prop="leavePrice">
          <template #default="{ row }">
            <span>{{ floatToFixed2(row.leavePrice) + '元' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单状态" min-width="85">
          <template #default>
            <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>

      <ContentWrap
        :bodyStyle="{ padding: '10px', borderRadius: '0px' }"
        class="!border-rd-none !border-t-none"
      >
        <el-row
          class="color-[#606266] dark:bg-[var(--el-bg-color)] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
        >
          <el-col :span="24">
            <div class="flex items-center">
              <!-- 门店下单 -->
              <div v-if="scope.row.deliveryType === DeliveryTypeEnum.SHOP.type">
                <span> 销售门店： </span>
                <span class="mr20px">
                  {{ scope.row.nodeName }}
                </span>
                <span> 销售员工：</span>
                <span class="mr20px">
                  <span v-for="item in scope.row.employeeStr" :key="item" class="mr-5px"
                    >ID:{{ item.employeeId }} {{ item.employeeName }} {{ item.proportion }}%</span
                  >
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
      </ContentWrap>
    </template>
  </el-table-column>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { DeliveryTypeEnum, NoteOnOrder } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { floatToFixed2 } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { OrderVO } from '@/api/mall/trade/order'
import type { ElTable, TableColumnCtx, TableInstance } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import type { DeliveryPickUpStoreVO } from '@/api/mall/trade/delivery/pickUpStore'
// import { debounce } from 'lodash-es'
import { phoneFormat } from '@/utils/formatter'

defineOptions({ name: 'OrderTableColumn' })

const props = defineProps<{
  list: OrderVO[]
}>()
const multipleSelection = ref()
const emit = defineEmits(['selectionChange'])

const handleSelectionChange = (val: any[], row) => {
  console.log(row)
  multipleSelection.value = val
  let params = {
    no: row.no,
    val: val
  }

  emit('selectionChange', params)

  // console.log(multipleSelection.value)
}
const activityOrderListRef = ref<InstanceType<typeof ElTable>>()

const getOrderTableRef = () => {
  return multipleSelection.value
}
defineExpose({ getOrderTableRef })

// const headerStyle = ({ row, columnIndex }: any) => {
//   // 表头第一行第一列占 10
//   // if (columnIndex === 0) {
//   //   row[columnIndex].colSpan = 10

//   // } else {
//   //   // 其余的不要
//   //   row[columnIndex].colSpan = 0
//   //   return {
//   //     display: 'none'
//   //   }
//   // }
//   return {
//     display: 'none'
//   }
// }

interface SpanMethodProps {
  row: TradeOrderApi.OrderItemRespVO
  column: TableColumnCtx<TradeOrderApi.OrderItemRespVO>
  rowIndex: number
  columnIndex: number
}

type spanMethodResp = number[] | { rowspan: number; colspan: number } | undefined
const spanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps): spanMethodResp => {
  const len = props.list.find(
    (order) => order.items?.findIndex((item) => item.id === row.id) !== -1
  )?.items?.length
  // 要合并的列，从零开始
  const colIndex = []
  if (colIndex.includes(columnIndex)) {
    // 除了第一行其余的不要
    if (rowIndex !== 0) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    // 动态合并行
    return {
      rowspan: len!,
      colspan: 1
    }
  }
}

/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

/** 复制 */
const message = useMessage() // 消息弹窗
import { useClipboard } from '@vueuse/core'
const { copy } = useClipboard() // 初始化 copy 到粘贴板
const copyContent = async (content) => {
  await copy(content)
  message.success('复制成功！')
}
</script>
<style lang="scss" scoped>
:deep(.table-col-row-class) {
  --el-table-row-hover-bg-color: transparent;
}
</style>
